package com.atguigu.gmall.pay.notity;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.config.rabbitMq.MqService;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.pay.config.properties.AlipayProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/api/payment")
public class PaySuccessNotity {
    @Autowired
    AlipayProperties  alipayProperties;
    @Autowired
    MqService  mqService;
    /**
     * 支付宝的异步通知
     * @param params
     * @return
     */
    @PostMapping("/notify/success")
    public String  paySuccessNotity(@RequestParam Map<String,String> params) throws AlipayApiException {
       log.info("收到支付宝异步通知", JSON.toJSONString(params));
       //TODO 验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayProperties.getAlipay_public_key(),
                alipayProperties.getCharset(),
                alipayProperties.getSign_type());//调用sdk签名验证
        if(signVerified){
            // TODO 修改订单状态  通过消息机制传递
            mqService.send(params, MqConst.ORDER_EVENT_EXCHANGE,MqConst.ORDER_PAYED_RK);
            log.info("验签通过,准备修改订单状态");

        }else {
            log.info("异常的支付宝订单");
        }
        return   "success";
    }

}
